package esms.etonenet.boss1069.hazelcast.bossres.service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import com.etonenet.entity.system.security.UserBs;
import com.etonenet.repository.system.security.UserBsRepository;
import com.etonenet.util.StringUtil;
import com.hazelcast.core.EntryEvent;
import com.hazelcast.core.EntryListener;
import com.hazelcast.core.IMap;
import com.hazelcast.core.MapEvent;

import esms.etonenet.boss1069.hazelcast.bossres.common.IHazelmapService;

//@Service
public class HUserBsService implements IHazelmapService<String, UserBs>, EntryListener<String, UserBs> {

	@Resource
	IMap<String, UserBs> userBsMap;

	@Resource
	UserBsRepository userBsEm;

	@PostConstruct
	@Override
	public void init() {
		userBsMap.addEntryListener(this, true);
		for (String loginName : userBsMap.keySet()) {

			UserBs mapUserBs = userBsMap.get(loginName);

			// 若数据库存在数据更新
			UserBs dbUserBs = userBsEm.findByLoginName(loginName);
			if (mapUserBs != null) {
				if (dbUserBs != null)
					mapUserBs.setUserId(dbUserBs.getUserId());
				userBsEm.save(mapUserBs);
			}
		}
	}

	@Override
	public void entryAdded(EntryEvent<String, UserBs> event) {

		userBsEm.save(event.getValue());
	}

	@Override
	public void entryEvicted(EntryEvent<String, UserBs> event) {
	}

	@Override
	public void entryRemoved(EntryEvent<String, UserBs> event) {
	}

	@Override
	public void entryUpdated(EntryEvent<String, UserBs> event) {
		String loginName = event.getKey();
		if (StringUtil.isNotEmpty(loginName)) {
			UserBs dbUserBs = userBsEm.findByLoginName(loginName);
			UserBs updateValue = event.getValue();
			if (dbUserBs != null && updateValue != null) {
				updateValue.setUserId(dbUserBs.getUserId());
				userBsEm.save(updateValue);
			}
		}
	}

	@Override
	public void mapCleared(MapEvent event) {
	}

	@Override
	public void mapEvicted(MapEvent event) {
	}

}
